package com.yxinsur.imc.business.events.listener;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yxinsur.imc.business.events.event.OrderCustomerEvent;
import com.yxinsur.imc.common.exception.BusinessException;
import com.yxinsur.imc.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class OrderCustomerEventListener implements ApplicationListener<OrderCustomerEvent> {
    @Value("${uranus.customerUrl}")
    private String customerUrl;

    @Async
    @Override
    public void onApplicationEvent(OrderCustomerEvent event) {
        String json = JSON.toJSONString(event.getCustomerDto());
        log.info("客户信息录入参数:"+json);
        String returnJson = null;
        try {
            returnJson = HttpUtil.post(customerUrl,json);
        } catch (Exception e) {
            log.error("客户录入信息错误:"+e.getMessage());
        }
        if(StringUtils.isEmpty(returnJson)){
            throw new BusinessException("客户信息例如失败");
        }
        JSONObject result = JSONObject.parseObject(returnJson);
        if(result!=null && result.getIntValue("code")==10000){
            log.info("客户信息录入成功：" + event.getCustomerDto().toString()+",信息提示为:"+event.getMsg());
        }else{
            throw new BusinessException("客户信息错误"+result.getString("msg"));
        }
    }
}
